import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter/widgets.dart' hide Action;
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:screen/screen.dart';
import 'package:www.znpigai.teacher/global_store/action.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/global_store/store.dart';
import 'package:www.znpigai.teacher/login_page/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<ProfileState> buildEffect() {
  return combineEffects(<Object, Effect<ProfileState>>{
    ProfileAction.onChangeAvatar: _onChangeAvatar,
    ProfileAction.onChangeGander: _onChangeGander,
    ProfileAction.onChangeMobile: _onChangeMobile,
    ProfileAction.onChangeName: _onChangeName,
    ProfileAction.onChangePassword: _onChangePassword,
    ProfileAction.onLogout: _onLogout,
    ProfileAction.onDark: _onDark,
    ProfileAction.onDestroy: _onDestroy,
  });
}

void _onChangeAvatar(Action action, Context<ProfileState> ctx) async {
  var url = await Navigator.of(ctx.context).pushNamed(Nav.AVATAR_LIST);
  if (url != null) {
    GlobalStore.store
        .dispatch(GlobalActionCreator.onChangeUserInfo({'headImage': url}));
    ctx.dispatch(ProfileActionCreator.refresh());
  }
}

void _onChangeGander(Action action, Context<ProfileState> ctx) async {
  String gander = await Util.showBottomSelectDialog(
      '请选择性别', {'male': '男', 'female': '女'}, ctx.context);

  if (gander.isNotEmpty) {
    // 修改性别
    var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
    pr.show();
    HttpResult result = await Http.post(
        '/correct/${GlobalState.userRole}/api/sex/update.mvc',
        data: {'sex': gander});
    pr.hide();

    if (result.success) {
      Util.alert('性别修改成功', ctx.context);
      GlobalStore.store
          .dispatch(GlobalActionCreator.onChangeUserInfo({'sex': gander}));
      ctx.dispatch(ProfileActionCreator.refresh());
    } else {
      Util.alertFail(result, ctx.context);
    }
  }
}

void _onChangeMobile(Action action, Context<ProfileState> ctx) async {
  Navigator.of(ctx.context).pushNamed(Nav.LOGIN,
      arguments: {'mode': LoginMode.CHANGE_MOBILE}).then((phone) {
    if (phone != null) {
      GlobalStore.store
          .dispatch(GlobalActionCreator.onChangeUserInfo({'mobile': phone}));
      ctx.dispatch(ProfileActionCreator.refresh());
    }
  });
}

void _onChangeName(Action action, Context<ProfileState> ctx) async {
  String name = '';
  bool ok = await Alert(
      context: ctx.context,
      title: "修改姓名",
      content: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              labelText: '请输入姓名',
            ),
            onChanged: (input) => name = input,
          ),
        ],
      ),
      buttons: [
        DialogButton(
          onPressed: () => Navigator.pop(ctx.context, false),
          child: Text(
            "取消",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
        DialogButton(
          color: Colors.blue,
          onPressed: () => Navigator.pop(ctx.context, true),
          child: Text(
            "修改",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        )
      ]).show();

  if (ok == true) {
    if (name.isEmpty) {
      Util.alert('姓名不能为空', ctx.context);
      return;
    }

    // 修改姓名
    var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
    pr.show();
    HttpResult result = await Http.post(
        '/correct/${GlobalState.userRole}/api/name/update.mvc',
        data: {'name': name});
    pr.hide();

    if (result.success) {
      Util.alert('姓名修改成功', ctx.context);
      GlobalStore.store
          .dispatch(GlobalActionCreator.onChangeUserInfo({'name': name}));
      ctx.dispatch(ProfileActionCreator.refresh());
    } else {
      Util.alertFail(result, ctx.context);
    }
  }
}

void _onChangePassword(Action action, Context<ProfileState> ctx) async {
  String old = '';
  String new1 = '';
  String new2 = '';
  bool ok = await Alert(
      context: ctx.context,
      title: "修改密码",
      content: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              labelText: '旧密码',
            ),
            onChanged: (input) => old = input,
          ),
          TextField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '新密码',
            ),
            onChanged: (input) => new1 = input,
          ),
          TextField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '确认新密码',
            ),
            onChanged: (input) => new2 = input,
          ),
        ],
      ),
      buttons: [
        DialogButton(
          onPressed: () => Navigator.pop(ctx.context, false),
          child: Text(
            "取消",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
        DialogButton(
          color: Colors.blue,
          onPressed: () => Navigator.pop(ctx.context, true),
          child: Text(
            "修改",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        )
      ]).show();

  if (ok == true) {
    if (old.isEmpty || new1.isEmpty || new2.isEmpty) {
      Util.alert('密码不能为空', ctx.context);
      return;
    }

    if (new1 != new2) {
      Util.alert('两次新密码不相同', ctx.context);
      return;
    }

    // 修改密码
    var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
    pr.show();
    HttpResult result = await Http.post(
        '/correct/${GlobalState.userRole}/api/pwd/update.mvc',
        data: {'current': old, 'newpwd': new1});
    pr.hide();

    if (result.success) {
      Util.alert('密码修改成功', ctx.context);
    } else {
      Util.alertFail(result, ctx.context);
    }
  }
}

void _onLogout(Action action, Context<ProfileState> ctx) {
  Util.showConfirmDialog('退出登录', '确定要退出登录？', ctx.context).then((ok) {
    if (ok == true) {
      GlobalState.isSignIn = false;
      Navigator.of(ctx.context).pushNamedAndRemoveUntil(
          GlobalState.isTeacher ? Nav.SOCIAL_LOGIN : Nav.LOGIN,
          (Route<dynamic> route) => false);
    }
  });
}

void _onDark(Action action, Context<ProfileState> ctx) async {
  if (GlobalState.dark == 0) {
    double brightness = await Screen.brightness;
    GlobalState.dark = brightness;
    await Screen.setBrightness(brightness / 2);
    ctx.state.darkOn = true;
  } else {
    await Screen.setBrightness(GlobalState.dark);
    GlobalState.dark = 0;
    ctx.state.darkOn = false;
  }
  ctx.dispatch(ProfileActionCreator.refresh());
}

void _onDestroy(Action action, Context<ProfileState> ctx) {
  Navigator.of(ctx.context).pushNamed(Nav.DESTROY);
}
